/*
 * This file Copyright (c) 2015. Walle.
 * (http://www.wallellen.com). All rights reserved.
 *
 *
 * This file is dual-licensed under both the
 * Walle Agreement (WA) and the GNU General Public License.
 * You may elect to use one or the other of these licenses.
 *
 * This file is distributed in the hope that it will be
 * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
 * Redistribution, except as permitted by whichever of the GPL
 * or WA you select, is prohibited.
 *
 * 1. For the GPL license (GPL), you can redistribute and/or
 * modify this file under the terms of the GNU General
 * Public License, Version 3, as published by the Free Software
 * Foundation.  You should have received a copy of the GNU
 * General Public License, Version 3 along with this program;
 * if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * 2. For the Walle Agreement (WA), this file
 * and the accompanying materials are made available under the
 * terms of the WA which accompanies this distribution, and
 * is available at http://www.wallellen.com/agreement.html
 *
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 */

package com.wallellen.core.xml;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;

/**
 * Created by walle on 12/17/15.
 */
public class JaxbParser {
    private static Logger logger = LoggerFactory.getLogger(JaxbParser.class);

    private Class clazz;
    private String[] cdataNode;

    /**
     * @param clazz
     */
    public JaxbParser(Class clazz) {
        this.clazz = clazz;
    }

    /**
     * 设置需要包含CDATA的节点
     *
     * @param cdataNode
     */
    public void setCdataNode(String[] cdataNode) {
        this.cdataNode = cdataNode;
    }

    /**
     * 转为xml串
     *
     * @param obj
     * @return
     */
    public String toXML(Object obj) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            m.setProperty(Marshaller.JAXB_FRAGMENT, true);// 去掉报文头
            OutputStream os = new ByteArrayOutputStream();
            StringWriter writer = new StringWriter();
            XMLSerializer serializer = getXMLSerializer(os);
            m.marshal(obj, serializer.asContentHandler());
            result = os.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("response text:" + result);
        return result;
    }


    /**
     * 转为对象
     *
     * @param is
     * @return
     */
    public Object toObj(InputStream is) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            Object obj = um.unmarshal(is);
            return obj;
        } catch (Exception e) {
            logger.error("post data parse error");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * XML转为对象
     *
     * @param xmlStr
     * @return
     */
    public Object toObj(String xmlStr) {
        InputStream is = new ByteArrayInputStream(xmlStr.getBytes());
        return toObj(is);
    }

    /**
     * 设置属性
     *
     * @param os
     * @return
     */
    private XMLSerializer getXMLSerializer(OutputStream os) {
        OutputFormat of = new OutputFormat();
        formatCDataTag();
        of.setCDataElements(cdataNode);
        of.setPreserveSpace(true);
        of.setIndenting(true);
        of.setOmitXMLDeclaration(true);
        XMLSerializer serializer = new XMLSerializer(of);
        serializer.setOutputByteStream(os);
        return serializer;
    }

    /**
     * 适配cdata tag
     */
    private void formatCDataTag() {
        for (int i = 0; i < cdataNode.length; i++) {
            cdataNode[i] = "^" + cdataNode[i];
        }
    }
}
